package proj2501.net_logo;

import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Rectangle2D;
import java.util.Hashtable;
import java.util.LinkedList;

import javax.swing.JPanel;

import proj2501.geo_util.Gr;
import proj2501.geo_util.VectorD2;

public class NLView extends JPanel {
	private NetLogo parent;
	private int width;
	private int height;
	
	public NLView(NetLogo parent) {
		this.parent = parent;
		addComponentListener(new ComponentAdapter() {
			@Override
			public void componentResized(ComponentEvent e) {
				super.componentResized(e);
				width = getWidth();
				height = getHeight();
				repaint();
			}
		});
	}
	
	public VectorD2 getScreenVector(VectorD2 v) {
		VectorD2 coordMove;
		if (parent.locationOfOrigin == NetLogo.ORIGIN_CENTER) {
			coordMove = new VectorD2(parent.minPxcor() - 0.5, parent.minPycor() - 0.5);
		} else {
			throw new RuntimeException("Not implemented.");
		}
		VectorD2 moved = v.sub(coordMove);
		double rx = width / parent.worldWidth();
		double ry = height / parent.worldHeight();
		return new VectorD2(moved.getX() * rx, moved.getY() * ry);
	}
	
	private Graphics2D g2;
	private Gr gr;
	
	@Override
	protected void paintComponent(Graphics g) {
		super.paintComponent(g);
		gr = new Gr(g);
		g2 = (Graphics2D) g;
//		g.drawOval(0, 0, 160, 160);
		paintPatches();
		paintTurtles();
	}
	
	private void paintPatches() {
		int minPxcor = parent.minPxcor();
		int maxPxcor = parent.maxPxcor();
		int minPycor = parent.minPycor();
		int maxPycor = parent.maxPycor();
		Hashtable<VectorD2, NLPatch> patches = parent.patches;
		double rx = width / parent.worldWidth();
		double ry = height / parent.worldHeight();
		double patchRadiusX = rx / 2;
		double patchRadiusY = ry / 2;
		
		for (int y = minPycor; y <= maxPycor; y++) {
			for (int x = minPxcor; x <= maxPxcor; x++) {
				VectorD2 v = new VectorD2(x, y);
				NLPatch patch = patches.get(v);
				VectorD2 loc = getScreenVector(patch.getVector());
				gr.drawCircle(loc, 5);
				Rectangle2D.Double rect = new Rectangle2D.Double(loc.getX() - patchRadiusX, loc.getY() - patchRadiusY, rx, ry);
				g2.setColor(patch.getColor().getSwingColor());
				g2.fill(rect);
			}
		}
	}
	
	private void paintTurtles() {
		double rx = width / parent.worldWidth();
		double ry = height / parent.worldHeight();
		double patchRadiusX = rx / 2;
		double patchRadiusY = ry / 2;
		LinkedList<NLTurtle> turtles = parent.turtles;
		for (NLTurtle turtle : turtles) {
			VectorD2 loc = getScreenVector(turtle.getVector());
			Ellipse2D.Double rect = new Ellipse2D.Double(loc.getX() - patchRadiusX, loc.getY() - patchRadiusY, rx, ry);
			g2.setColor(turtle.getColor().getSwingColor());
			g2.draw(rect);
			
			VectorD2 ov = turtle.getOrientationVector();
			VectorD2 line = new VectorD2(ov.getX() * patchRadiusX, ov.getY() * patchRadiusY);
			gr.drawLine(loc, loc.add(line));
		}
	}
}
